//The Quad Class, inherits from the Plane class

#include "Quad.h"

//The Quad contructor
Quad::Quad(Vector3 center, Vector3 normal, float width, float height) {
	name = "Quad";
	positiveDiscriminant = true;
	t1 = t2 = -1;
	issphere = false;

	this->center = center;
	n = normal;
	this->width = width;
	this->height = height;
	distanceFromOrigin = center.length();

	n.normalize();
}


//Determines the distance at which a ray intersects the Quad
Object* Quad::tIntersect(const Ray& ray, float& distance) {
	Vector3 rayDirection = ray.direction;
	Vector3 rayOrigin = ray.origin;

	float d = Vector3::dotProduct(n, rayDirection);
	t1 = t2 = ((Vector3::dotProduct(n, rayOrigin) + distanceFromOrigin) * (-1)) / d;

	Vector3 hit = rayOrigin + (rayDirection*t1);

	if (hit.x >= center.x - width/2 && hit.x <= center.x + width/2 && hit.z >= center.z - height/2 && hit.z <= center.z + height/2) {
		distance = Vector3(hit-rayOrigin).length();
		positiveDiscriminant = true;
	}
	else {
		distance = -1;
		positiveDiscriminant = false;
	}

	return this;
}

Color Quad::getExtraColor(Vector3 p) {
	Color toReturn;

	for (int i = 0; i < causticTriangles.size(); i++) {
		if (inTriangle(p, causticTriangles[i])) {
			toReturn = Color(1, 1, 1)*causticTriangles[i].intensity;
			break;
		}
	}

	return toReturn;
}

bool Quad::inTriangle(Vector3 p, Triangle tri) {
	Vector3 p0 = tri.p0;
	Vector3 p1 = tri.p1;
	Vector3 p2 = tri.p2;

	Vector3 zeroToMid = p - p0;
	Vector3 oneToMid = p - p1;

	float totalArea = Vector3::crossProduct(p0-p1, zeroToMid).length()/2.0;
	totalArea += Vector3::crossProduct(p0-p2, zeroToMid).length()/2.0;
	totalArea += Vector3::crossProduct(p1-p2, oneToMid).length()/2.0;

	if (totalArea - tri.getArea() >= -0.005 && totalArea - tri.getArea() <= 0.005) {
		return true;
	}

	return false;
}